package com.example.pceb.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.pceb.VO.RecruitVo;
import com.example.pceb.entity.*;
import com.example.pceb.mapper.*;
import com.example.pceb.result.Result;
import com.example.pceb.result.ResultCode;
import com.example.pceb.service.ResumeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//学生端
//招聘信息搜索

@Service
public class ResumeServiceImpl extends ServiceImpl<ResumeMapper, Resume> implements ResumeService {
    @Autowired
    private RecruitMapper recruitMapper;
    @Autowired
    private ResumeMapper resumeMapper;
    @Autowired
    private RecruitInformationMapper recruitInformationMapper;
    @Autowired
    private CollectMapper collectMapper;
    @Autowired
    private LikeMapper likeMapper;
    @Autowired
    private CommunicationMapper communicationMapper;

    //获取所有招聘信息
    @Override
    public Result<List<Recruit>> selectRecruit(RecruitVo recruitVo) {
        return Result.success(recruitMapper.selectByRecruitVo(recruitVo));
    }

    //通过关键词查询职位信息
    @Override
    public Result<List<Recruit>> selectRecruitByKeyWords(String keyWords) {
        LambdaQueryWrapper<Recruit> queryWrapper = new LambdaQueryWrapper<>();
        // 使用.or()来组合多个like查询
        queryWrapper.like(Recruit::getIdentity, keyWords)
                .or()
                .like(Recruit::getDetails, keyWords);
        // 执行查询
        return Result.success(recruitMapper.selectList(queryWrapper));

    }

    //学生发送简历
    @Override
    public Result<String> sendRecruit(@RequestParam("username")String username, @RequestParam("recruitId")int recruitId) {
        LambdaQueryWrapper<Resume> resumeQueryWrapper = new LambdaQueryWrapper<>();
        resumeQueryWrapper.eq(Resume::getUsername, username);
        Resume resume = resumeMapper.selectOne(resumeQueryWrapper);
        if (resume == null) {
            return Result.fail("当前用户未上传简历！", ResultCode.OK);
        }
        LambdaQueryWrapper<Recruit> recruitQueryWrapper = new LambdaQueryWrapper<>();
        recruitQueryWrapper.eq(Recruit::getId, recruitId);
        Recruit recruit = recruitMapper.selectOne(recruitQueryWrapper);
        if (recruit == null) {
            return Result.fail("招聘不存在",ResultCode.OK);
        }
        // 创建recruit_information记录
        RecruitInformation recruitInformation = new RecruitInformation();
        recruitInformation.setRecruitId(recruitId);
        recruitInformation.setResumeId(resume.getId());
        recruitInformation.setTime(new Date());

        // 插入recruit_information记录
        boolean result = recruitInformationMapper.insert(recruitInformation) > 0;
        if (result) {
            return Result.success("发送成功");
        } else {
            return Result.fail("发送失败",ResultCode.OK);
        }
    }
    //获取招聘职位详细信息
    @Override
    public Result<Map<String, Object>> getRecruitDetail(int recruitId, String username){
        //获取招聘基本信息
        Recruit recruit=recruitMapper.selectById(recruitId);
        if(recruit==null){
            return Result.fail("招聘信息不存在",ResultCode.NOT_FOUND);
        }

        //获取收藏状态
        boolean isCollected= collectMapper.exists(new LambdaQueryWrapper<Collect>()
                .eq(Collect::getUsername,username)
                .eq(Collect::getRecruitId,recruitId));

//        //获取点赞状态
//        boolean isLiked=likeMapper.exists(new LambdaQueryWrapper<LikeRecord>()
//                .eq(LikeRecord::getUsername,username)
//                .eq(LikeRecord::getRecruitId,recruitId));
//
//        //获取未读消息数量
//        Long unreadCount=communicationMapper.selectCount(new LambdaQueryWrapper<Communication>()
//                .eq(Communication::getUsername,username)
//                .eq(Communication::getRecruitId,recruit)
//                .eq(Communication::getSenderType,1)
//                .eq(Communication::getIsRead,0));

        //返回结果
        Map<String,Object>result=new HashMap<>();
        result.put("recruit",recruit);
        result.put("isCollected",isCollected);
//        result.put("isLiked",isLiked);
//        result.put("unreadMessageCount",unreadCount);

        return Result.success(result);
    }
    //收藏/取消招聘信息
    @Override
    public Result<String> toggleCollect(String username,int recruitId){
        LambdaQueryWrapper<Collect> wrapper=new LambdaQueryWrapper<Collect>()
                .eq(Collect::getUsername,username)
                .eq(Collect::getRecruitId,recruitId);

        //检查是否收藏
        Collect existing=collectMapper.selectOne(wrapper);
        if(existing!=null){
            //已收藏则取消收藏
            collectMapper.deleteById(existing.getId());
            return Result.success("已取消收藏");
        }else{
            //未收藏则添加收藏
            Collect collect=new Collect();
            collect.setUsername(username);
            collect.setRecruitId(recruitId);
            collect.setCreateTime(new Date());
            collectMapper.insert(collect);
            return Result.success("收藏成功");
        }
    }

    //点赞招聘信息
    @Override
    public Result<String> likeRecruit(String username,int recruitId){
        LambdaQueryWrapper<LikeRecord> wrapper=new LambdaQueryWrapper<LikeRecord>()
                .eq(LikeRecord::getUsername,username)
                .eq(LikeRecord::getRecruitId,recruitId);

        //检查是否已经点赞
        LikeRecord existing=likeMapper.selectOne(wrapper);
        if(existing!=null){
            //已点赞则取消点赞
            likeMapper.deleteById(existing.getId());
            return Result.success("已取消点赞");
        }else{
            LikeRecord like=new LikeRecord();
            like.setUsername(username);
            like.setRecruitId(recruitId);
            like.setCreateTime(new Date());
            likeMapper.insert(like);
            return Result.success("点赞成功");
        }
    }

    //与hr进行沟通
    @Override
    public Result<String> communicateWithHR(String username,int recruitId,String message){
        //检查招聘信息是否存在
        Recruit recruit=recruitMapper.selectById(recruitId);
        if(recruit==null){
            return Result.fail("招聘信息不存在",ResultCode.NOT_FOUND);
        }

        //创建沟通记录
        Communication communication=new Communication();
        communication.setUsername(username);
        communication.setRecruitId(recruitId);
        communication.setMessageContent(message);
        communication.setIsRead(0);//默认未读
        communication.setSenderType(0);//用户发送
        communicationMapper.insert(communication);

        // 模拟HR回复（实际应用可对接真实HR系统）
        Communication hrReply = new Communication();
        hrReply.setUsername(username);
        hrReply.setRecruitId(recruitId);
        hrReply.setSenderType(1); // 1表示HR发送
        hrReply.setMessageContent("您好！您的咨询信息已收到，我们将在24小时内给您回复。");
        hrReply.setIsRead(0); // 用户未读

        communicationMapper.insert(hrReply);

        //发送沟通信息
        return Result.success("消息发送成功",hrReply.getMessageContent());
    }

    //获取与HR聊天记录
    public Result<List<Communication>> getCommunicationHistory(String username, Integer recruitId){
        //获取沟通记录
        LambdaQueryWrapper<Communication> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Communication::getUsername,username)
                .eq(Communication::getRecruitId,recruitId)
                .orderByAsc(Communication::getSentTime);

        List<Communication> communications=communicationMapper.selectList(wrapper);

        //将所有HR发送的消息标记为已读
        communications.stream()
                .filter(comm->comm.getSenderType()==1&&comm.getIsRead()==0)
                .forEach(comm->{
                    comm.setIsRead(1);
                    communicationMapper.updateById(comm);
                });

        return Result.success(communications);
    }

    //检查收藏状态
    public boolean isCollected(String username, int recruitId){
        LambdaQueryWrapper<Collect> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Collect::getUsername, username)
                .eq(Collect::getRecruitId, recruitId);
        return collectMapper.selectCount(wrapper) > 0;
    }

    //获取相似职位信息
    public List<Recruit> getSimilarRecruits(String enterprise, Integer currentId){
        QueryWrapper<Recruit> wrapper = new QueryWrapper<>();
        wrapper.eq("enterprise", enterprise)
                .ne("id", currentId)
                .eq("isPass", 1) // 只查审核通过的
                .orderByDesc("isHot") // 可选：热门优先
                .last("LIMIT 10");    // 最多返回10条
        return recruitMapper.selectList(wrapper);
    }

    //根据用户名加载简历
    public Resume getByUsername(String username){
        QueryWrapper<Resume> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        return resumeMapper.selectOne(wrapper);
    }

    //保存简历
    public void saveOrUpdateResume(Resume resume){
        QueryWrapper<Resume> wrapper = new QueryWrapper<>();
        wrapper.eq("username", resume.getUsername());
        Resume exist = resumeMapper.selectOne(wrapper);
        if (exist == null) {
            resumeMapper.insert(resume);
        } else {
            resume.setId(exist.getId());
            resumeMapper.updateById(resume);
        }
    }

}
